package com.termux.ui.ide.tab

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.termux.R
import org.apache.commons.io.FileUtils
import java.io.File

class ConfigTab(file: File) : FileTab(file) {
    var jsonObject: JSONObject? = null

    init {
        jsonObject = JSON.parseObject(FileUtils.readFileToString(file, "utf-8"))
    }

    override fun onSelected() {
        val executableFile = contentView?.findViewById(R.id.exec_file_path_view) as EditText?
        executableFile?.setText(jsonObject?.getString("exec_file_path"))
        executableFile?.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                changed = true
                jsonObject?.put("exec_file_path",p0.toString())
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })
        val spinner = contentView?.findViewById(R.id.project_type_view) as Spinner
        when (jsonObject?.getString("type")) {
            "Console" -> spinner.setSelection(0, true)
            "NativeActivity" -> spinner.setSelection(1, true)
            "OpenGLES" -> spinner.setSelection(2, true)
            "SDL2" -> spinner.setSelection(3, true)
        }
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(p0: AdapterView<*>?) {
            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                var type = ""
                when (p2) {
                    0 -> type = "Console"
                    1 -> type = "NativeActivity"
                    2 -> type = "OpenGLES"
                    3 -> type = "SDL2"
                }
                if (!jsonObject?.getString("type").equals(type)) {
                    changed = true
                }
                jsonObject?.put("type", type)
            }

        }
    }

    override fun save() {
        FileUtils.write(file, jsonObject?.toJSONString(), "utf-8")
    }

    override fun onClose() {
    }

}